/**
 * Created by Sergey on 23.02.14.
 */

function initElements() {
    $(".jquery-button").button().css({fontSize: "0.85em"});
    var tabs = $(".jquery-tabs");
    tabs.tabs();
    tabs.find("ul li a").click(function () {
        location.hash = $(this).attr("href");
    });

    $("input, textarea, select, button, .group-lbl, .error-message, .jquery-button").tooltip({
        position: {
            at: "right top",
            my: "left bottom"
        }
    });

    $(".jquery-datepicker")
        .datepicker({dateFormat: "dd.mm.yy"});

    var quizStartDate = $("#quiz_start_date");
    var quizEndDate = $("#quiz_end_date");

    if (quizStartDate.length > 0 && quizEndDate.length > 0) {
        if (quizStartDate.val().length == 0 && quizEndDate.val().length == 0) {
            var today = new Date();
            var afterWeek = new Date(today.getTime() + (7 * 24 * 60 * 60 * 1000));

            quizStartDate.datepicker("setDate", today);
            quizEndDate.datepicker("setDate", afterWeek);
        }
    }

    $("#questions-table")
        .find("> tbody > tr:odd")
        .addClass("grey-row");
}

function toggleQuizDetails() {
    $("#show-quiz-results-details").click(function () {
        $("#quiz-results-details").toggle();
    });
}

function validateForms() {
    $("#group-form").submit(function () {
        $(".error-message").remove();
        var success = true;
        var form = $(this);
        var nameField = form.find("[name='name']");

        if (nameField.val() <= 0) {
            success = false;
            addErrorNotification(nameField, "Поле должно быть заполнено");
        }

        return success;
    });

    $("#quiz-form").submit(function () {
        $(".error-message").remove();
        var success = true;
        var form = $(this);

        var requiredFields =
            form.find("[name='name'], [name='start_date'], [name='end_date']");
        requiredFields.each(function () {
            if ($(this).val().length == 0) {
                addErrorNotification($(this), "Поле должно быть заполнено");
                success = false;
            }
        });

        var dateFields = form.find("[name='start_date'], [name='end_date']");
        dateFields.each(function () {
            if (!$(this).val().match(/^(\d{1,2}).(\d{1,2}).(\d{4})$/)) {
                addErrorNotification($(this), "Формат даты указан не верно");
                success = false;
            }
        });

        var groupSelect = form.find("[name^='groups']");
        if (groupSelect.find("option:selected").length == 0) {
            addErrorNotification(groupSelect, "Укажите хотя бы одну группу");
            success = false;
        }

        return success;
    });

    $("#question-form").submit(function () {
        $(".error-message").remove();

        var success = true;
        var form = $(this);

        var requiredFields =
            form.find("input[type='text'], textarea");
        requiredFields.each(function () {
            if ($(this).val().length == 0) {
                addErrorNotification($(this), "Поле должно быть заполнено");
                success = false;
            }
        });

        return success;
    });
}

function addErrorNotification(element, error) {
    element.parent().children(":last").after(
        "<div class='error-message'>" + error + "</div>"
    );
}

function editUserData() {
    $(".student-table .group-lbl, .student-table .error-message").click(function () {
        var label = $(this);
        label.hide();
        label.closest("td").find(".groups")
            .show().focus()
            .blur(function () {
                var studentId = $(this).closest("tr").find("[name^='students']").val();
                var groupId = $(this).find("option:selected").val();

                var form = $("form[name='student-form']");
                form.find("input[name='studentId']").val(studentId);
                form.find("input[name='groupId']").val(groupId);
                form.submit();
            });
    });

    $(".tutor-table .group-lbl").click(function () {
        var column = $(this).closest("td");
        column.find(".group-lbl").hide();
        var select = column.find("select");
        select.show().focus();
        select.blur(function () {
            $(this).closest("form").submit();
        });
    });
}


/* QUESTION FORM */

function indexingAnswerList() {
    $(".answers-list li").each(function (index) {
        var idInputName = "answers[" + $(this).index() + "][id]";
        $(this).find("input[type='hidden']").attr("name", idInputName);

        var correctInputName = "answers[" + $(this).index() + "][correct]";
        $(this).find("input[type='checkbox']").attr("name", correctInputName);

        var contentInputName = "answers[" + $(this).index() + "][content]";
        $(this).find("input[type='text']").attr("name", contentInputName);
    });
}

function addRemoveBtnHandler() {
    $(".remove-answer").click(function () {
        var list = $(".answers-list");
        if (list.find("li").length > 2) {
            $(this).closest("li").remove();
            indexingAnswerList();
        }
    });
}

function addCreateBtnHandler() {
    $(".create-answer").click(function () {
        var list = $(".answers-list");
        var answerItem = list.find("li:first").clone();
        answerItem.find("input[type='checkbox']").attr("checked", false);
        answerItem.find("input[type='text']").val("");
        list.append(answerItem);

        indexingAnswerList();
        addRemoveBtnHandler();
    });
}

/* ~QUESTION FORM */


$(function () {
    initElements();
    toggleQuizDetails();
    validateForms();
    editUserData();

    addCreateBtnHandler();
    addRemoveBtnHandler();
    indexingAnswerList();
});